package chances.epg.commons.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.velocity.tools.generic.DateTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;



import chances.epg.commons.template.TemplateEngine;
import chances.epg.commons.utils.JSONUtils;

public abstract class AbstractTemplateController {
	private Logger logger = LoggerFactory.getLogger(AbstractTemplateController.class);
	
	@Autowired
	protected TemplateEngine templateEngine;
	
	/**
     * 请求应答.
     * 
     * @param rsp
     * @param ctx
     * @throws IOException
     */
    protected String responseByVelocity(HttpServletRequest request,HttpServletResponse response,String templatePath,Map<String,Object> params)
            throws IOException {
    	response.setContentType("text/html");
    	response.setCharacterEncoding("UTF-8");
        StringWriter writer = new StringWriter();
        
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put("dt", new DateTool());
        properties.put("json", JSONUtils.class);
        properties.putAll(params);
        templateEngine.execute(properties,templatePath, writer);
        String json = writer.toString();
        
        //解决跨域调用
        String callback = request.getParameter("callback");
        if(StringUtils.isNotBlank(callback)){
        	json = callback + "(" + json + ")";
        }
        
        response.getWriter().write(json);
        response.getWriter().close();
        return json;
    }
    
    protected String readRequestInputStream(HttpServletRequest request) throws IOException {
    	InputStream is = null;
		String body = "";
		try {
			is = request.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is,
					"UTF-8"));
			// 读取HTTP请求内容
			String buffer = null;
			StringBuffer sb = new StringBuffer();
			while ((buffer = br.readLine()) != null) {
				sb.append(buffer);
			}

			body = sb.toString();
			
			logger.debug("request path:{},body:{}",new Object[]{request.getRequestURI(),body});
		}finally{
			try {
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {

			}
		}
		
		return body;
    }
}
